//
//  QuickViewTransactionVC.m
//  Wallets Manager
//
//  Created by Nguyen Chi Cong on 10/29/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "QuickViewTransactionVC.h"
#import "DataBaseAccess.h"
#import "folyAppDelegate.h"

@implementation QuickViewTransactionVC
{
    NSDateFormatter *dateFormatter;
    
}
@synthesize table;
@synthesize imvAvata;
@synthesize lbTotal;
@synthesize lbAvg;
@synthesize nameOfType;
@synthesize total;
@synthesize arrInputs;
@synthesize allKeys;
@synthesize sources;
@synthesize fromDate;
@synthesize toDate;
@synthesize reportType;
@synthesize name;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // init sources
    dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    
    sources = [self processIncomes:arrInputs];
    allKeys = [sources allKeys];
    
    //init UI
    
    NSString *cur = [(folyAppDelegate *)[[UIApplication sharedApplication] delegate] currentWallet].wToCurrency.c_symbol;
    lbTotal.text = [NSString stringWithFormat:@"%.f %@",[total doubleValue], cur];
    lbAvg.text = [NSString stringWithFormat:@"%.1f %@/session", [total doubleValue]/[allKeys count], cur];
    nameOfType.text = name;
    
}

- (void)viewDidUnload
{
    [self setTable:nil];
    [self setImvAvata:nil];
    [self setLbTotal:nil];
    [self setLbAvg:nil];
    [self setNameOfType:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.arrInputs      = nil;
    self.total          = nil;
    dateFormatter       = nil;
    allKeys             = nil;
    sources             = nil;
    fromDate            = nil;
    toDate              = nil;
    name                = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - IBAction
- (IBAction)dismiss:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - TableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [allKeys count];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *key = [allKeys objectAtIndex:section];
    NSArray *values = [sources objectForKey:key];
    return [values count];
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [allKeys objectAtIndex:section];
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    
//    UILabel *label = [[UILabel alloc] init];
//    label.frame = CGRectMake(20, 6, 300, 30);
//    label.backgroundColor = [UIColor clearColor];
//    label.textColor = [UIColor whiteColor];
//    label.shadowColor = [UIColor grayColor];
//    label.shadowOffset = CGSizeMake(0.0, 1.0);
//    label.font = [UIFont boldSystemFontOfSize:14];
//    label.text = [allKeys objectAtIndex:section]; //sectionHeader;
//    
//    return label;
//    
//}

-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
//    if(section == ([allKeys count]-1))
//    {
//        return [NSString stringWithFormat: @"Reporting Wallet Manager"];
//    }
    return nil;
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ReportCellIdentifier = @"ReportCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReportCellIdentifier];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ReportCellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    UITextField *amountTextField;
    
    cell.textLabel.font = [UIFont fontWithName:@"Courier" size:16.f];
    NSInteger section = [indexPath section];
    NSInteger row = [indexPath row];
    NSString *key = [allKeys objectAtIndex:section];
    NSArray *values = [sources objectForKey:key];
    
    
//    id ic = [incomes objectAtIndex:indexPath.row];
//    folyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
//    NSManagedObjectContext *context = [appDelegate managedObjectContext];
//    NSEntityDescription *entity = [NSEntityDescription entityForName:kIncome inManagedObjectContext:context];
//    if([ic isKindOfEntity:entity])
//    {
//        Income *icb = (Income *)ic;
//        NSLog(@"DDDCCCMMM: %@", icb.i_name);
//    }
    
    
    
    amountTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 20, 280, 20)];
    amountTextField.textColor = [UIColor whiteColor];
    amountTextField.backgroundColor = [UIColor clearColor];
    amountTextField.font = [UIFont systemFontOfSize:12];
    amountTextField.tag = 300;
    amountTextField.enabled = NO;
    [cell addSubview:amountTextField];
    
     amountTextField.borderStyle = UITextBorderStyleBezel;
    
    if(reportType ==0)
    {
        Income *income = [values objectAtIndex:row];
        cell.textLabel.text = income.i_name;
        
        cell.detailTextLabel.text = [NSString stringWithFormat:@"Date: %@", [dateFormatter stringFromDate:income.i_date]];
        cell.detailTextLabel.font = [UIFont fontWithName:@"Courier" size:12.f];
        amountTextField.text = [NSString stringWithFormat:@"%.f",[income.i_amount doubleValue]];
        amountTextField.backgroundColor = [UIColor colorWithRed:14.0/255.0 green:154.0/255.0 blue:209.0/255.0 alpha:1];
        NSString *imgURL = [((Plan*)[income iToPlan]) p_image];
        cell.imageView.image = [UIImage imageNamed:imgURL];
        
    }else
    {
        Expense *exp = [values objectAtIndex:row];
        cell.textLabel.text = exp.e_name;
        
        cell.detailTextLabel.text = [NSString stringWithFormat:@"Date: %@", [dateFormatter stringFromDate:exp.e_date]];
        cell.detailTextLabel.font = [UIFont fontWithName:@"Courier" size:12.f];
        amountTextField.text = [NSString stringWithFormat:@"%.f",[exp.e_amount doubleValue]];
        amountTextField.backgroundColor = [UIColor colorWithRed:202.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1];
        NSString *imgURL = [((Plan*)[exp eToPlan]) p_image];
        cell.imageView.image = [UIImage imageNamed:imgURL];
    }
    
    CGSize amountTextFieldSize = [amountTextField.text sizeWithFont:[UIFont systemFontOfSize:12]];
    amountTextField.frame = CGRectMake(290-amountTextFieldSize.width,10 , amountTextFieldSize.width+15, 20);

    
    return cell;
}

#pragma mark - TableViewDelegate

#pragma mark - Input Processing
-(NSDictionary *)processIncomes: (NSArray *)arrIncomes
{
    NSMutableArray *marrIncomes = [[NSMutableArray alloc] initWithArray:arrIncomes];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
   
    if(reportType == 0)
    {
    Income *ic;
    NSDate *date = nil;
    int index = 0;
    do {
        ic = [marrIncomes objectAtIndex:index];
        //NSLog(@"%@", [[ic entity] name]);
        if(ic.i_date != date)
        {
            date = ic.i_date;
            
             NSMutableArray *marrValues = [[NSMutableArray alloc] init];
            
            for(Income *icTemp in marrIncomes)
            {
                //if([icTemp.i_date timeIntervalSince1970] == [date timeIntervalSince1970])
                if([icTemp.i_date isEqualToDate:date])
                {
                    [marrValues addObject:icTemp];
                }
            }
            
            [dict setValue:marrValues forKey:[dateFormatter stringFromDate:date]];
        }
        index++;
        
    } while (index < [marrIncomes count]);
    }else
    {
        Expense *ic;
        NSDate *date = nil;
        int index = 0;
        do {
            ic = [marrIncomes objectAtIndex:index];
            if(ic.e_date != date)
            {
                date = ic.e_date;
                
                NSMutableArray *marrValues = [[NSMutableArray alloc] init];
                
                for(Expense *icTemp in marrIncomes)
                {
                    //if([icTemp.i_date timeIntervalSince1970] == [date timeIntervalSince1970])
                    if([icTemp.e_date isEqualToDate:date])
                    {
                        [marrValues addObject:icTemp];
                    }
                }
                
                [dict setValue:marrValues forKey:[dateFormatter stringFromDate:date]];
            }
            index++;
            
        } while (index < [marrIncomes count]);
    }
    
    NSLog(@"%@", dict);
    return dict;
    
}


@end
